闘本 3.6 動物保護施設
提出
code: txt
class MyQueue:
def __init__(self):
self.new_stack = Stack()
self.old_stack = Stack()
def _shift_stacks(self):
if self.old_stack.is_empty():
while not self.new_stack.is_empty():
self.old_stack.push(self.new_stack.pop())
def add(self, value):
return self.new_stack.push(value)
def peek(self):
if self.is_empty():
return False
self._shift_stacks()
return self.old_stack.peek()
def remove(self):
if self.is_empty():
return False
self._shift_stacks()
return self.old_stack.pop()
def is_empty(self):
return len(self) == 0
def __len__(self):
return len(self.new_stack) + len(self.old_stack)
class Animal(MyQueue):
def __init__(self):
self.dog = Stack()
super()
def enqueue(self, value):
super().add(value)
解答
code: python
class LinkedListNode:
def __init__(self, animal):
self.animal = animal
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def add_to_tail(self, animal):
new_node = LinkedListNode(animal)
if self.tail:
self.tail.next = new_node
self.tail = new_node
if not self.head:
self.head = new_node
def remove_from_head(self):
if self.is_empty():
return None
animal = self.head.animal
self.head = self.head.next
if self.head is None:
self.tail = None
return animal
class Animal:
def __init__(self, name):
self.name = name
self.order = None
def set_order(self, order):
self.order = order
def get_order(self):
return self.order
def is_older_than(self, animal):
return self.order < animal.get_order()
class Dog(Animal):
pass
class Cat(Animal):
pass
class AnimalQueue:
def __init__(self):
self.dogs = LinkedList()
self.cats = LinkedList()
self.order = 0
def enqueue(self, animal):
animal.set_order(self.order)
self.order += 1
if isinstance(animal, Dog):
self.dogs.add_to_tail(animal)
elif isinstance(animal, Cat):
self.cats.add_to_tail(animal)
def dequeue_any(self):
if self.dogs.is_empty():
return self.dequeue_cats()
elif self.cats.is_empty():
return self.dequeue_dogs()
dog = self.dogs.head.animal
cat = self.cats.head.animal
if dog.is_older_than(cat):
return self.dequeue_dogs()
else:
return self.dequeue_cats()
def dequeue_dogs(self):
return self.dogs.remove_from_head()
def dequeue_cats(self):
return self.cats.remove_from_head()
animal_queue = AnimalQueue()
animal_queue.enqueue(Dog("Fido"))
animal_queue.enqueue(Cat("Whiskers"))
animal_queue.enqueue(Dog("Rover"))
animal_queue.enqueue(Cat("Fluffy"))
print(animal_queue.dequeue_any().name) # Fido
print(animal_queue.dequeue_cats().name) # Whiskers
print(animal_queue.dequeue_dogs().name) # Rover
print(animal_queue.dequeue_any().name) # Fluffy